package com.szewec.ps.ui.tabbar;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.szewec.ps.R;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.ListBaseAdapter;
import com.szewec.ps.base.SuperViewHolder;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.project.ProjectListModel;
import com.szewec.ps.model.projectandstage.Project;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.tabbar.beans.PlanTask;
import com.szewec.ps.ui.task.TaskEditActivity;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.SharedPreferencesUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.dialog.LoadingDialog;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.List;

public class StartInvestigationDialog extends DialogFragment {
    private Dialog dialog;
    private View view;

    private Window window;

    private View llTitle;
    private TextView tvTitle;
    private Button btnDetermine;

    private String selectedProjectId;
    private boolean isOpened = false;

    private Drawable down;
    private Drawable up;

    private LRecyclerView projectListView;
    private ProjectAdapter projectDataAdapter;
    private List<Project> projectList = new ArrayList<>();

    private LRecyclerView taskListView;
    private TaskAdapter taskDataAdapter;
    private List<PlanTask> taskList = new ArrayList<>();
    private PlanTask planTask;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        planTask = null;
        taskList = new ArrayList<>();
        initData();
        getTaskData(selectedProjectId);
    }

    @SuppressLint("InflateParams")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.dialog_start_investigation, container);
        up = getActivity().getDrawable(R.mipmap.pull_up);
        down = getActivity().getDrawable(R.mipmap.drop_down);
        initView();
        return view;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        dialog = new Dialog(getActivity(), R.style.bottom_dialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setWindowAnimations(R.style.main_menu_animstyle);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消
        setCancelable(true);

        // 设置宽度为屏宽, 靠近屏幕底部。
        window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        window.setAttributes(getLayoutParams(window.getAttributes()));
//        ButterKnife.bind(this, dialog); // Dialog即View
        return dialog;
    }


    private void initView() {
        llTitle = view.findViewById(R.id.ll_title);
        tvTitle = view.findViewById(R.id.tv_title);

        view.findViewById(R.id.btn_new_task).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), TaskEditActivity.class);
            ProjectListModel.ProjectModel projectModel = new ProjectListModel.ProjectModel();
            projectModel.setId(selectedProjectId);
            PresentValue<ProjectListModel.ProjectModel> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.ADD, projectModel);
            intent.putExtra(Constants.PRESENT_VALUE, presentValue);
            startActivity(intent);
        });

        btnDetermine = view.findViewById(R.id.btn_determine);
        view.findViewById(R.id.btn_start_investigation).setOnClickListener(v -> {
//            this.dialog.dismiss();
//            StartBtnDialog dialog = new StartBtnDialog();
//            dialog.show(getChildFragmentManager(), "startBtnDialog");
            if (planTask == null || StringUtils.isEmpty(planTask.getId())) {
                BamToast.showText(getContext(), "请先选择!", false);
                return;
            }
            StartDialog dialog = new StartDialog(getContext()).setPlanTask(this.planTask);
            dialog.show();
//            this.dialog.cancel();
            this.dismiss();
        });

        llTitle.setOnClickListener(v -> {
            if (isOpened) {
                closeSelectProject();
            } else {
                openSelectProject();
            }
        });
        String selectedProjectName = (String) SharedPreferencesUtil.getData(PreferincesContext.PROJECT_NAME, "");
        tvTitle.setText(selectedProjectName);
        view.findViewById(R.id.mark_view).setOnClickListener(v -> closeSelectProject());

        projectListView = view.findViewById(R.id.lrv_drop_down_list);
        projectDataAdapter = new ProjectAdapter(getContext());
        projectDataAdapter.setDataList(projectList);
        projectListView.setAdapter(new LRecyclerViewAdapter(projectDataAdapter));
        projectListView.setLayoutManager(new LinearLayoutManager(getContext()));
        projectListView.setLoadMoreEnabled(false);
        projectListView.setPullRefreshEnabled(false);

        taskListView = view.findViewById(R.id.lrv_plan_list);
        taskDataAdapter = new TaskAdapter(getContext());
        taskDataAdapter.setDataList(taskList);
        taskListView.setAdapter(new LRecyclerViewAdapter(taskDataAdapter));
        taskListView.setLayoutManager(new LinearLayoutManager(getContext()));
        taskListView.setLoadMoreEnabled(false);
        taskListView.setPullRefreshEnabled(false);
//        getTaskData(selectedProjectId);
    }

    private void openSelectProject() {
        isOpened = true;
        tvTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, up, null);
//                popupWindow.showAsDropDown(llTitle);
        view.findViewById(R.id.ll_drop_down_list).setVisibility(View.VISIBLE);
    }

    private void closeSelectProject() {
        isOpened = false;
        tvTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, down, null);
        view.findViewById(R.id.ll_drop_down_list).setVisibility(View.GONE);
    }

    protected WindowManager.LayoutParams getLayoutParams(WindowManager.LayoutParams params) {
        if (params == null) {
            return new WindowManager.LayoutParams();
        }
        //注意这里设置的宽高，需要设置成MATCH_PARENT,不然的话就不会起作用，就这一点坑。
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.BOTTOM;// 紧贴底部
        return params;
    }

    private void initData() {
        String projectListString = (String) SharedPreferencesUtil.getData(PreferincesContext.PROJECT_AND_STAGE_INFO, "");
        selectedProjectId = (String) SharedPreferencesUtil.getData(PreferincesContext.PROJECT_ID, "");
        if (StringUtils.isNotEmpty(projectListString)) {
            List<Project> projects = JSON.parseArray(projectListString, Project.class);
            for (Project project : projects) {
                if (project.getId().equals(selectedProjectId)) {
                    project.setChecked(true);
                }
            }
            projectList = projects;
        }
    }

    private void getTaskData(String projectId) {
        OkHttp.get("/tpms-plan-service/api/task/get/" + projectId, null, LoadingDialog.getInstance(getContext()), result -> {
            JSONObject json = JSONObject.parseObject(result);
            taskList = JSON.parseArray(json.getString("data"), PlanTask.class);
            if (taskList == null) {
                taskList = new ArrayList<>();
            }
            for (int i = taskList.size() - 1; i >= 0; i--) {
                if (taskList.get(i).getTaskStatus() == 4) {
                    taskList.remove(i);
                }
            }

            taskDataAdapter.setDataList(taskList);
            taskDataAdapter.notifyDataSetChanged();
            System.out.println(result);
        });
    }

    private void doSelectedProject(Project project) {
        for (Project project1 : projectList) {
            project1.setChecked(project1.getId().equals(project.getId()));
        }
        projectDataAdapter.setDataList(projectList);
        projectDataAdapter.notifyDataSetChanged();
        tvTitle.setText(project.getProjectName());
        selectedProjectId = project.getId();
        getTaskData(project.getId());
        closeSelectProject();
    }

    private void doSelectedPlanTask(PlanTask planTask) {
        for (PlanTask planTask1 : taskList) {
            planTask1.setChecked(planTask1.getId().equals(planTask.getId()));
        }
        taskDataAdapter.setDataList(taskList);
        taskDataAdapter.notifyDataSetChanged();
        this.planTask = planTask;
//        closeSelectProject();
    }

    private class TaskAdapter extends ListBaseAdapter<PlanTask> {

        public TaskAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_simple_check;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView title = holder.getView(R.id.tv_title);
            ImageView checkedIv = holder.getView(R.id.iv_checked);

            title.setTextSize(15);
            title.setTextColor(0xFF3A3A3A);
            PlanTask planTask = mDataList.get(position);
            title.setText(planTask.getTaskMatter());
            if (planTask.isChecked()) {
                checkedIv.setImageResource(R.mipmap.ic_select);
            } else {
                checkedIv.setImageResource(R.mipmap.ic_no_select);
            }
            //行点击监听事件
            holder.itemView.setOnClickListener(view -> doSelectedPlanTask(planTask));
        }
    }

    private class ProjectAdapter extends ListBaseAdapter<Project> {

        public ProjectAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_common_string_2;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();
            params.height = 130;
            holder.itemView.setLayoutParams(params);
            TextView title = holder.getView(R.id.tv_common_title);
            ImageView checkedIv = holder.getView(R.id.iv_checked);
            View lineView = holder.getView(R.id.line_view);

            //设置下划线的边距
            ViewGroup.LayoutParams lineParams = lineView.getLayoutParams();
            ViewGroup.MarginLayoutParams marginParams;
            //获取view的margin设置参数
            if (lineParams instanceof ViewGroup.MarginLayoutParams) {
                marginParams = (ViewGroup.MarginLayoutParams) lineParams;
            } else {
                //不存在时创建一个新的参数
                marginParams = new ViewGroup.MarginLayoutParams(lineParams);
            }
            marginParams.setMargins(0, 0, 0, 0);
            marginParams.setMarginStart(0);
            marginParams.setMarginEnd(0);
            lineView.setLayoutParams(marginParams);

            title.setTextSize(14);

            Project project = mDataList.get(position);
            title.setText(project.getProjectName());
            if (project.isChecked()) {
                checkedIv.setVisibility(View.VISIBLE);
                title.setTextColor(0xFF2A84FC);
            } else {
                checkedIv.setVisibility(View.GONE);
                title.setTextColor(0xFF333333);
            }
            //行点击监听事件
            holder.itemView.setOnClickListener(view -> doSelectedProject(project));
        }
    }
}
